#include "Widget.h"
#include "ui_Widget.h"

Widget::Widget(QWidget *parent) :
      QWidget(parent),
      ui(new Ui::Widget)
{
   ui->setupUi(this);
}

Widget::~Widget()
{
   delete ui;
}

void Widget::initSocket()
{
   udpSocket = new QUdpSocket(this);
   udpSocket->bind(QHostAddress::LocalHost, 7755);

   connect(udpSocket, SIGNAL(readyRead()), this, SLOT(readPendingDatagrams()));

   qDebug() << "ip server : " << udpSocket->localAddress();

   QList<QHostAddress> listaIPs = interface.allAddresses();
   for (int i = 0; i < listaIPs.size(); i++)
   {
      qDebug() << listaIPs[i].toString();
   }
}

void Widget::readPendingDatagrams()
{
   qDebug() << "Server On!!!";
   while (udpSocket->hasPendingDatagrams()) {
      qDebug() << "---";
      QByteArray datagram;
      datagram.resize(udpSocket->pendingDatagramSize());
      QHostAddress sender;
      quint16 senderPort;

      udpSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);

      qDebug() << "sender ip : " << sender.toString();

      processTheDatagram(datagram);

      udpSocket->writeDatagram(datagram.data(), datagram.size(), sender, senderPort);
   }
   qDebug() << "Server Off!!!";
}

void Widget::processTheDatagram(QByteArray datagram)
{
   qDebug() << "datagram : " << datagram.data();
}

void Widget::on_pushButton_clicked()
{
   initSocket();
}
